package io.renren.modules.app.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.renren.common.utils.EmailUtils;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.Query;
import io.renren.common.utils.YxuntongSms;
import io.renren.modules.app.dao.TDeclareDao;
import io.renren.modules.app.entity.*;
import io.renren.modules.app.service.*;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.mail.EmailException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Service("tDeclareService")
public class TDeclareServiceImpl extends ServiceImpl<TDeclareDao, TDeclareEntity> implements TDeclareService {

    @Autowired
    private TProductService tProductService;
    @Autowired
    private TOrganizationService tOrganizationService;
    @Autowired
    private TInsuranceService tInsuranceService;
    @Autowired
    private TCompanyService tCompanyService;

    private String msg = "【政企通】{0}申请{1}需求已发送到您的邮箱,请注意查收!";


    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<TDeclareEntity> page = this.page(
                new Query<TDeclareEntity>().getPage(params),
                new QueryWrapper<TDeclareEntity>().eq(params.get("companyId") != null,"company_id",params.get("companyId"))
        );

        return new PageUtils(page);
    }

    @Override
    @Transactional
    public void submit(TDeclareEntity tDeclare){
        try {

            Integer declareTypeId = tDeclare.getDeclareTypeId();
            tDeclare.setCreateTime(new Date());
            this.save(tDeclare);

            if(declareTypeId.intValue()==1){
                Integer pid = tDeclare.getProductId();
                //在产品详情页面提报
                if(pid!=null){
                    Map<String, Object> p = new HashMap<>();
                    p.put("id",pid);
                    List<TProductEntity> list = (List<TProductEntity>) tProductService.listByMap(p);
                    for(TProductEntity t:list){
                        //todo 发信息/发邮件
                        sendMsgMail(t.getIdOrganization(),tDeclare.getCompanyId(),declareTypeId,t.getProductName());
                    }
                }else{
                    //列表页面提报-贷款
                    Map<String, Object> p = new HashMap<>();
                    p.put("declare_type_id",declareTypeId);
                    List<TOrganizationEntity> list = (List<TOrganizationEntity>) tOrganizationService.listByMap(p);
                    for(TOrganizationEntity t:list){
                        //todo 发信息/发邮件
                        sendMsgMail(t.getId(),tDeclare.getCompanyId(),declareTypeId,"");
                    }
                }
            }

            if(declareTypeId.intValue()==3){
                Integer iid = tDeclare.getInsuranceId();
                //在产品详情页面提报
                if(iid!=null){
                    Map<String, Object> p = new HashMap<>();
                    p.put("id",iid);
                    List<TInsuranceEntity> list = (List<TInsuranceEntity>) tInsuranceService.listByMap(p);
                    for(TInsuranceEntity t:list){
                        sendMsgMail(t.getIdOrganization(),tDeclare.getCompanyId(),declareTypeId,t.getProductName());
                    }
                }else{
                    //列表页面提报-保险
                    Map<String, Object> p = new HashMap<>();
                    p.put("declare_type_id",declareTypeId);
                    List<TOrganizationEntity> list = (List<TOrganizationEntity>) tOrganizationService.listByMap(p);
                    for(TOrganizationEntity t:list){
                        //todo 发信息/发邮件
                        sendMsgMail(t.getId(),tDeclare.getCompanyId(),declareTypeId,"");
                    }
                }
            }

            if(declareTypeId.intValue()==2||declareTypeId.intValue()==4||declareTypeId.intValue()==5){
                //列表页面提报-担保/基金/奖励
                Map<String, Object> p = new HashMap<>();
                p.put("declare_type_id",declareTypeId);
                List<TOrganizationEntity> list = (List<TOrganizationEntity>) tOrganizationService.listByMap(p);
                for(TOrganizationEntity t:list){
                    //todo 发信息/发邮件
                    sendMsgMail(t.getId(),tDeclare.getCompanyId(),declareTypeId,"");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 发短信邮件
     * @param organizaId
     * @param companyId
     */
    public void sendMsgMail(Integer organizaId,Integer companyId,Integer declareTypeId,String productName){
        TOrganizationEntity to = tOrganizationService.getById(organizaId);
        TCompanyEntity company = tCompanyService.getById(companyId);
        //todo 发信息/发邮件
        String content = msg.replace("{0}",company.getCompanyName());
        content = content.replace("{1}","的");
        YxuntongSms.sendMsg(to.getTel(),content);
        try {
            StringBuffer body = new StringBuffer();
            body.append("<html>");
            body.append("<body>");
            body.append("<div style=\"text-indent: 2em;\">您收到一条来自【政企通】的信息，详细信息如下：</div>");
            body.append("<table style=\"margin-left:2em;width:500px;\" border=\"1\" cellspacing=\"0\">");
            body.append("<tr><td width=\"30%\" align=\"right\">企业类型:</td><td align=\"left\">"+company.getCompanyType()+"</td></tr>");
            body.append("<tr><td width=\"30%\" align=\"right\">企业名称:</td><td align=\"left\">"+company.getCompanyName()+"</td></tr>");
            body.append("<tr><td width=\"30%\" align=\"right\">企业规模:</td><td align=\"left\">"+company.getCompanyScale()+"</td></tr>");
            body.append("<tr><td width=\"30%\" align=\"right\">所属行业:</td><td align=\"left\">"+company.getInBusiness()+"</td></tr>");
            body.append("<tr><td width=\"30%\" align=\"right\">统一社会代码:</td><td align=\"left\">"+company.getSocialCode()+"</td></tr>");
            body.append("<tr><td width=\"30%\" align=\"right\">主营业务:</td><td align=\"left\">"+company.getMainBusiness()+"</td></tr>");
            body.append("<tr><td width=\"30%\" align=\"right\">联系人:</td><td align=\"left\">"+company.getContacter()+"</td></tr>");
            body.append("<tr><td width=\"30%\" align=\"right\">联系电话:</td><td align=\"left\">"+company.getTelphone()+"</td></tr>");

            String declare = "";
            switch (declareTypeId){
                case 1:
                    declare = "贷款";
                    break;
                case 2:
                    declare = "担保";
                    break;
                case 3:
                    declare = "保险";
                    break;
                case 4:
                    declare = "基金";
                    break;
                case 5:
                    declare = "奖励";
                    break;
            }
            if(StringUtils.isNotBlank(productName)){
                productName = "【"+productName+"】";
            }
            //EmailUtils.sendSimpleTextEmail(to.getEmail(),"【政企通】 "+company.getCompanyName()+" 提报"+productName+declare+"需求",body.toString(),"");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
